var CreateReturnToProvder = function () {
  var template = /* html */ `
  <div class="reutrnMaterialToProvider" v-loading.fullscreen.lock="loading">
    <div>
      <search-btn-view immediate btn-text="查询条件" @before-open="resetSearch" @search="searchData">
        <div slot="search-content">
          <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:16}" :search="search"
            :search-field="searchField" label-width="100px" input-width="180px">
            <template slot="prepend">
              <el-form-item label="采购日期">
                <el-date-picker v-model="search.startDate" style="width:229px;" value-format="timestamp" :editable="false"
                  :picker-options="startDateOption" placeholder="采购开始日期"></el-date-picker>
                -
                <el-date-picker v-model="search.endDate" style="width:229px;" value-format="timestamp" :editable="false"
                  :picker-options="endDateOption" placeholder="采购结束日期"></el-date-picker>
              </el-form-item>
            </template>
          </sys-common-search>
        </div>
      </search-btn-view>
    </div>
    <div class="returnToProvider-mgr-table-div">
      <el-table fit stripe border :data="returnMaterialToProviderData" style="width:100%;" height="parent">
        <el-table-column sortable prop="purchaseId" label="采购单号" min-width="220px" header-align="center"></el-table-column>
        <el-table-column sortable prop="companyOrderId" label="订单编号" min-width="140px" header-align="center"></el-table-column>
        <el-table-column sortable prop="factoryNo" label="工厂型号" min-width="120px" header-align="center"></el-table-column>

        <el-table-column sortable prop="providerName" label="供应商" min-width="100px" header-align="center"></el-table-column>
        <el-table-column sortable prop="materialName" label="物料名称" min-width="130px" header-align="center"></el-table-column>
        <el-table-column sortable prop="color" label="编号" min-width="100px" header-align="center"></el-table-column>
        <el-table-column sortable prop="colorDescription" label="描述" min-width="120px" header-align="center"></el-table-column>
        <el-table-column sortable prop="model" label="规格" min-width="120px" header-align="center"></el-table-column>        
        <el-table-column sortable prop="materialDeptName" label="物料部门" min-width="120px" align="center"></el-table-column>

        <el-table-column sortable prop="unit" label="单位" min-width="100px" align="center"></el-table-column>
        <el-table-column sortable prop="purchaseCount" label="采购数量" min-width="120px" align="center"></el-table-column>
        <el-table-column sortable prop="inCount" label="入库数量" min-width="120px" align="center"></el-table-column>
        <el-table-column sortable prop="materialCount" label="库存数量" min-width="120px" align="center"></el-table-column>
        <el-table-column :resizable="false" label="退回单价" min-width="150px" header-align="center">
          <template slot-scope="scope">
            <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :precision="4" v-model="scope.row.unitPrice" style="width:140px"
              @change="moneyChange(scope.row,'unitPrice')">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="退回数量" min-width="150px" header-align="center">
          <template slot-scope="scope">
            <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :precision="4" v-model="scope.row.count" style="width:140px">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="退回结算数量" min-width="150px" header-align="center">
          <template slot-scope="scope">
            <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" max="scope.row.maxCount" :precision="4" v-model="scope.row.valuationCount"
              style="width:140px" @change="moneyChange(scope.row,'valuationCount')">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="退回金额" min-width="150px" header-align="center">
          <template slot-scope="scope">
            <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :precision="2" v-model="scope.row.totalMoney" style="width:140px"
              @change="moneyChange(scope.row,'totalMoney')">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="操作" width="155px" fixed="right" header-align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="returnOutToProvider(scope.row,false)">退货</el-button>
            <el-button type="primary" size="mini" @click="returnOutToProvider(scope.row,true)" :disabled="!selfApprovalPermission">审核过账</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
   <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange"></table-pagination>
</div>
  `;
  return {
    mixins: [
      tablePaginationMixin(),
      datePickerOptionsMixin('startDate', 'endDate')
    ],
    data: function () {
      var search = {
        materialName: '',
        model: '',
        color: '',
        colorDescription: '',
        providerName: '',
        materialDept: '',
        companyOrderId: '',
        orderId: '',
        factoryNo: '',
        customerNo: '',
        startDate: null,
        endDate: null
      };
      return {
        loading: false,
        moment: moment,
        returnMaterialToProviderData: [],
        selfApprovalPermission: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        searchField: ['materialName', 'model', 'color', 'providerName', 'materialDept', 'orderId', 'companyOrderId',
          'factoryNo', 'customerNo'
        ],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10
        }
      };
    },
    created: function () {
      this.checkApprovalPermission();
    },
    methods: {
      checkApprovalPermission: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(10).then(function (hasApproval) {
          self.selfApprovalPermission = hasApproval;
          return hasApproval;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setMaterialDataList(true);
      },

      pageChange: function () {
        this.setMaterialDataList();
      },

      setMaterialDataList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }
        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        }
        postData = this.setPostData(postData, search);

        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/getMaterialCanReturnToProviderData",
          postData, false).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var materialList = res.returnData;
          for (var i = 0; i < materialList.length; i++) {
            var material = materialList[i];
            SysUtil.tableSetDeptData(material);

            var count = material.count;
            if (SysUtil.isEmpty(count)) {
              count = undefined;
            }
            material.count = count;

            var valuationCount = material.sumMoneyCount;
            var unitPrice = material.inCountPrice;
            var totalMoney = undefined;
            if (SysUtil.isEmpty(valuationCount)) {
              valuationCount = undefined;
              totalMoney = 0;
            } else {
              totalMoney = _.round(valuationCount * unitPrice, 2);
            }
            material.maxCount = valuationCount;
            material.valuationCount = valuationCount;

            material.unitPrice = unitPrice;
            material.totalMoney = totalMoney;
          }

          self.returnMaterialToProviderData = materialList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      setPostData: function (postData, search) {
        var fields = ['orderId', 'companyOrderId', 'factoryNo', 'customerNo', 'materialName', 'model', 'color',
          'colorDescription', 'providerName'
        ];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        var startDate = search.startDate;
        if (startDate !== null) {
          postData.startDate = moment(startDate).format('YYYY-MM-DD');
        }

        var endDate = search.endDate;
        if (endDate !== null) {
          postData.endDate = moment(endDate).format('YYYY-MM-DD');
        }

        return postData;
      },

      reset: function () {
        this.isShowUpdateBox = false;
        this.setMaterialDataList();
      },

      returnOutToProvider: function (material, isAduit) {
        var code = this.checkValid(material);
        if (code !== '') {
          var msg = i18n.getMsg(`returnOrder.createOrder.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        var postData = {
          id: material.id,
          count: material.count,
          sumMoneyCount: material.valuationCount,
          inCountPrice: material.unitPrice,
          inOutMoney: material.totalMoney
        };

        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/AddMateiralToProvider", {
          returnMaterialToProvider: JSON.stringify(postData),
          isAduit: isAduit
        }).then(function (msg) {
          self.$alert(msg, "信息", {
            callback: function () {
              if (isAduit) {
                self.setMaterialDataList();
              }
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      checkValid: function (material) {
        var fields = ['unitPrice', 'count', 'valuationCount', 'totalMoney'];
        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          var value = material[field];
          if (value === undefined) {
            return field;
          }

          if (['valuationCount', 'totalMoney'].indexOf(field) !== -1) {
            continue;
          }

          if (value === 0) {
            return field + 'IsZero';
          }
        }

        var count = material.count;
        if (count > material.inCount) {
          return 'count>inCount';
        }

        if (count > material.materialCount) {
          return 'count>materialCount';
        }
        return '';
      },

      moneyChange: function (material, type) {
        var count = material.valuationCount;
        if (['unitPrice', 'valuationCount'].indexOf(type) !== -1) {
          var unitPrice = material.unitPrice;
          var totalMoney = SysUtil.calPrice(count, unitPrice, 'total', 2);
          material.totalMoney = totalMoney;
        } else {
          var totalMoney = material.totalMoney;
          var unitPrice = SysUtil.calPrice(count, totalMoney, 'unit', 4);
          material.unitPrice = unitPrice;
        }
      }
    },
    components: {
      SearchBtnView: SearchBtnView,
      SysCommonSearch: SysCommonSearch
    },
    template: template
  }
}();
